package com.zl.tby.service.impl;

import com.zl.tby.core.base.bean.OptionTypeLevel;
import com.zl.tby.core.base.bean.TbyPageResult;
import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.model.TbyTypeLevel;
import com.zl.tby.repository.TbyTypeLevelRepo;
import com.zl.tby.service.ITbyTypeLevelService;
import com.zl.tby.vo.TbyTypeLevelBean;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.annotation.Db;
import org.noear.wood.utils.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 物种级别管理接口实现类
 * @author sunjiaxing
 * @version 1.0
 * @since 2024/8/11 14:22
 */
@Component
public class TbyTypeLevelServiceImpl implements ITbyTypeLevelService {

    @Db
    private TbyTypeLevelRepo tbyTypeLevelRepo;

    @Override
    @Tran
    public R<TbyTypeLevel> add(TbyTypeLevel entity) {
        entity.setCreateBy(ToolsUtil.getLoginUserId());
        entity.setCreateTime(LocalDateTime.now());
        entity.setParentIds(getIds(entity.getParentId()));
        if(entity.getParentId() == 0 ){
            entity.setLevelNames(entity.getLevelName());
        }else{
            entity.setLevelNames(getNames(entity.getParentId(),entity.getLevelName()));
        }
        long id = tbyTypeLevelRepo.insert(entity, true);
        entity.setId(id);
        return R.ok(entity);
    }

    public String getIds(Long parentId) {
        String ids = "";
        if(parentId == 0 ){
            return "0";
        }
        List<TbyTypeLevel> dbList = tbyTypeLevelRepo.selectList(mp -> { mp.whereTrue(); });
        for (TbyTypeLevel entity : dbList) {
            if(entity.getId().equals(parentId)) {
                ids = entity.getParentIds()+","+parentId;
            }
        }
        return ids;
    }

    public String getNames(Long parentId,String name) {
        String names = "";
        List<TbyTypeLevel> dbList = tbyTypeLevelRepo.selectList(mp -> { mp.whereTrue(); });
        for (TbyTypeLevel entity : dbList) {
            if(entity.getId().equals(parentId)) {
                names = entity.getLevelNames()+","+name;
            }
        }
        return names;
    }

    public String updateChilden(Long id,String oldName,String newName) {
        String names = "";
        List<TbyTypeLevel> dbList = tbyTypeLevelRepo.selectList(mp -> mp.whereTrue());
        for (TbyTypeLevel entity : dbList) {
            if(entity.getLevelNames()!=null && entity.getLevelNames().contains(oldName)){
                String[] arr = entity.getLevelNames().split(",");
                int index = Arrays.binarySearch(arr, oldName);
                if (index >= 0) {
                    arr[index] = newName;
                    entity.setLevelNames(String.join(",",arr));
                    tbyTypeLevelRepo.updateById(entity, false);
                }
            }
        }
        return names;
    }

    @Override
    @Tran
    public R<TbyTypeLevel> update(TbyTypeLevel entity) {
        TbyTypeLevel old = this.tbyTypeLevelRepo.selectById(entity.getParentId());
        String[] arr = old.getParentIds().split(",");
        for (String item:arr) {
            if (item.equals(entity.getId().toString())){
                return R.failed("所选的上级级别在本层级下，请先修改层级");
            }
        }
            TbyTypeLevel oldBean = this.get(entity.getId());
        entity.setUpdateBy(ToolsUtil.getLoginUserId());
        entity.setUpdateTime(LocalDateTime.now());
        entity.setParentIds(getIds(entity.getParentId()));
        if(entity.getParentId() == 0 ){
            entity.setLevelNames(entity.getLevelName());
        }else{
            entity.setLevelNames(getNames(entity.getParentId(),entity.getLevelName()));
        }
        Integer flag =  tbyTypeLevelRepo.updateById(entity, false);
        if(flag>0){
            //更新子级  集合名称
            updateChilden(entity.getId(),oldBean.getLevelName(),entity.getLevelName());
        }
        return R.ok(entity);
    }

    @Override
    public R<Void> delete(Long id) {
        if (this.tbyTypeLevelRepo.selectCount(mp -> mp.whereTrue().andEq("parent_id", id)) > 0) {
            return R.failed("存在子分类无法删除");
        }
        return tbyTypeLevelRepo.deleteById(id) == 1 ? R.ok() : R.failed("删除失败");
    }

    @Override
    public R<Void> restParents() {
//        List<TbyTypeLevel> resultList = new ArrayList<>();
        List<TbyTypeLevel> dbLists = tbyTypeLevelRepo.selectList(mp -> { mp.whereTrue(); });
        for (TbyTypeLevel item : dbLists) {
            if(item.getParentId() == 0L){
                item.setParentIds("0");
                item.setLevelNames(item.getLevelName());
                tbyTypeLevelRepo.updateById(item, false);
            }else{
                TbyTypeLevel dto = tbyTypeLevelRepo.selectById(item.getParentId());
                if (dto!=null) {
                    item.setParentIds(dto.getParentIds() + "," + item.getParentId());
                    item.setLevelNames(dto.getLevelNames()+","+item.getLevelName());
//                    resultList.add(item);
                    tbyTypeLevelRepo.updateById(item, false);
                }
            }
        }
//        tbyTypeLevelRepo.updateList(resultList,null,null);
        return R.ok();
    }

    @Override
    public TbyTypeLevelBean get(Long id) {
        TbyTypeLevelBean result = new TbyTypeLevelBean();
        TbyTypeLevel dto = tbyTypeLevelRepo.selectById(id);
        result.setId(dto.getId());
        result.setLevel(dto.getLevel());
        result.setLevelName(dto.getLevelName());
        result.setLevelNames(dto.getLevelNames());
        result.setParentId(dto.getParentId());
        TbyTypeLevel parent = tbyTypeLevelRepo.selectById(dto.getParentId());
        result.setParentName(parent.getLevelName());
        return result;
    }

    @Override
    public TbyPageResult<TbyTypeLevelBean> treeTableList() {
        List<TbyTypeLevelBean> resultList = TbyTypeLevelBean.recurData(0L, this.tbyTypeLevelRepo.selectList(mp -> { mp.whereTrue(); }));
        return new TbyPageResult(resultList, new BigDecimal(resultList.size()).longValue(), 1, 1000);
    }

    @Override
    public List<OptionTypeLevel> options(String name) {if(StringUtils.isNotEmpty(name)){
            List<TbyTypeLevel> resultList =  this.tbyTypeLevelRepo.selectList(mp -> { mp.whereTrue()
                    .andIf(StringUtils.isNotEmpty(name),"level_name like ?", "%" + name + "%"); });
            String parentIds = "";
            for (int i = 0; i < resultList.size(); i++) {
                parentIds = parentIds + resultList.get(i).getParentIds()+",";
            }
            if(StringUtils.isNotEmpty(parentIds)){
                parentIds = parentIds.substring(0,parentIds.length()-1);
                Set<String> set = new HashSet<>();
                for (String str : parentIds.split(",")) {
                    set.add(str);
                }
                // 将set转换回数组
                String[] newArry = set.toArray(new String[0]);
                List<TbyTypeLevel> resultList1 = this.tbyTypeLevelRepo.selectByIds(Arrays.asList(newArry));
                // 去除两个list中id相同的元素
                for(TbyTypeLevel item:resultList1){
                    Boolean have = true;
                    for(TbyTypeLevel itemOld:resultList){
                        if(item.getId().compareTo(itemOld.getId())==0){
                            have = false;
                            break;
                        }
                    }
                    if(have){
                        resultList.add(item);
                    }
                }
            }
            return TbyTypeLevelBean.recurRouteOptions(0L, resultList );
        }else{
            return TbyTypeLevelBean.recurRouteOptions(0L, this.tbyTypeLevelRepo.selectList(mp -> { mp.whereTrue(); }));
        }
    }
}
